<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-08
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddProjectCategory'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增分类
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1000"
      :columns="columns"
      :get-data="api.pageQueryCategories"
    >
      <MeQueryItem label="分类名称" :label-width="70">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入分类名称"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="上级分类" :label-width="70">
        <n-select
          v-model:value="queryItems.parentId"
          :options="categories"
          label-field="name"
          value-field="id"
          clearable
          filterable
          placeholder="请选择上级分类"
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="500px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="分类名称"
          path="name"
          :rule="{
            required: true,
            message: '请输入分类名称',
            trigger: ['blur'],
          }"
        >
          <n-input v-model:value="modalForm.name" placeholder="请输入分类名称" />
        </n-form-item>

        <n-form-item
          label="上级分类"
          path="parentId"
        >
          <n-select
            v-model:value="modalForm.parentId"
            :options="categories"
            label-field="name"
            value-field="id"
            clearable
            filterable
            placeholder="请选择上级分类"
          />
        </n-form-item>

        <n-form-item
          label="分类描述"
          path="description"
        >
          <n-input
            v-model:value="modalForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入分类描述"
          />
        </n-form-item>

        <n-form-item label="排序" path="sortOrder">
          <n-input-number
            v-model:value="modalForm.sortOrder"
            placeholder="请输入排序号"
            :min="0"
            :max="999"
          />
        </n-form-item>

        <n-form-item label="启用状态" path="enable">
          <NSwitch v-model:value="modalForm.enable">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </NSwitch>
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch, NTag } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import api from './api'

defineOptions({ name: 'ProjectCategory' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

// 项目分类选项
const categories = ref([])

// 加载分类选项
function loadCategories() {
  api.getProjectCategories().then(({ data = [] }) => {
    categories.value = data
  })
}

// 初始化加载分类
loadCategories()

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '项目分类',
  initForm: {
    name: '',
    description: '',
    parentId: null,
    sortOrder: 0,
    enable: true,
  },
  doCreate: api.createCategory,
  doDelete: api.deleteCategory,
  doUpdate: api.updateCategory,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { title: '分类名称', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '上级分类',
    key: 'parent',
    width: 150,
    ellipsis: { tooltip: true },
    render: (row) => {
      if (!row.parentId) {
        return h(NTag, { type: 'default' }, { default: () => '顶级分类' })
      }
      const parent = categories.value.find(item => item.id === row.parentId)
      return parent ? h(NTag, { type: 'info' }, { default: () => parent.name }) : '未知'
    },
  },
  {
    title: '分类描述',
    key: 'description',
    width: 250,
    ellipsis: { tooltip: true },
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: 80,
    render: (row) => {
      return h('span', { class: 'text-gray-500' }, row.sortOrder || 0)
    },
  },
  {
    title: '状态',
    key: 'enable',
    width: 100,
    render: row =>
      h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.enable,
          loading: !!row.enableLoading,
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '停用',
        },
      ),
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.createTime))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleView(row),
          },
          {
            default: () => '查看',
            icon: () => h('i', { class: 'i-carbon:document-view text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            class: 'ml-12px',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

async function handleEnable(row) {
  row.enableLoading = true
  try {
    await api.updateCategory({ id: row.id, enable: !row.enable })
    row.enableLoading = false
    $message.success('操作成功')
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

function handleView(row) {
  handleOpen({ action: 'view', title: '查看项目分类', row })
}

function handleEdit(row) {
  handleOpen({ action: 'edit', title: '编辑项目分类', row })
}
</script>